from django.shortcuts import render
from django.http import HttpResponse,HttpResponseRedirect
from .models import *
from tower.models import *
from .verify import *
import json

#资产管理系统
def asset_manage(request):
    context = {'message':'欢迎来到本系统'}
    return render(request,'asset/asset_manage.html',context)

#资产添加
def function(request):

    return render(request,'asset/资产.html')

#资产添加运算
def asset(request):
	
    info = dict(request.POST)
    print(info)
    '''
        info = {'asset_name': ['×××'], 'asset_num': ['××']}
    '''
        

    return HttpResponse('ok')

#添加资产接口
@verify
def api_asset_add(request):
    '''
       
       提交方式:POST
       提交数据格式:{'add_asset_name':'XXX'}
    '''
    if request.method == 'POST':
        
        try:
            info = request.POST['add_asset_name'].strip()
        except KeyError:
            return HttpResponse("提交信息格式有误,或者键不是'add_asset_name'")
        else:
            if info != '':
                try:
                    Asset.objects.create(asset_name=info)
                    return HttpResponse('添加成功')
                except django.db.utils.IntegrityError:#UNIQUE报错
                    return '资产({})已存在'.format(info)
                
            else:
                return HttpResponse('添加的资产不能为空')
    elif request.method == 'GET':
        return HttpResponse('访问模式应该为POST')
 

#资产删除
def asset_del(request):
        context = {}
        return render(request,'asset/asset_del.html',context)

#资产删除运算
def asset_del_db(request):
    info = dict(request.POST)
    print(info)
        
    return HttpResponse('ok')

#资产删除接口
@verify
def api_asset_del(request):
    """
        删除:{'楼号':'xx','楼层':'xx','房间号':'xx','名称':'xxx','数量':'xxx',}
    """
    if request.method == 'POST':
        info = request.POST
        print(info)
        try:
            tower = Tower.objects.get(tower_name=info['tower_num'])
        except Tower.DoesNotExist:
            return HttpResponse('没有这个楼')
        else:
            try:
                floor = Floor.objects.get(floor_num=info['floor_num'])
            except Floor.DoesNotExist:
                return HttpResponse('没有这个层')
            else:
                try:
                    room = Room.objects.get(room_num=info['room_num'])
                    print(room)
                except Room.DoesNotExist:
                    return HttpResponse('没有这个房间')
                else:
                    try:
                        asset = Asset.objects.get(asset_name=info['asset_name'])
                    except Asset.DoesNotExist:
                        return HttpResponse('没有这个物品')
                    else:
                       
                        rom = Interchange.objects.filter(room=room).filter(asset=asset)
                       
                        print(rom[0])
                        
                        if rom[0].asset_num < int(info['asset_num']):
                            return HttpResponse('数量不足')
                        
                        else:

                            asset_new = rom[0].asset_num - int(info['asset_num'])
                            rom.update(asset_num=asset_new)
                            
                            if asset_new == 0:
                                rom[0].delete()
                            
                            return HttpResponse('删除成功')
                            
    elif request.method == 'GET':
        return HttpResponse('获取方式有误')
        
        
                               

#资产查询
def asset_find(request):
    context = {}
    return render(request,'asset/asset_find.html',context)

#资产查询运算
def asset_find_db(request):
    info = dict(request.POST)
    print(info)
    return HttpResponse('ok')

#资产查询接口
@verify
def api_asset_find(request):
    """
        查询:{'楼号':'xxx','层号':'xxx','房间号':'xxx','资产':'xxx'}
    """
    if request.method == 'POST':
        info = request.POST
        print(info)
        
        try:
            tower = Tower.objects.get(tower_name=info['tower_num'])
        except Tower.DoesNotExist:
            return HttpResponse('没有这个楼')
        else:
            try:
                floor = Floor.objects.get(floor_num=info['floor_num'])
            except Floor.DoesNotExist:
                return HttpResponse('没有这个层')
            else:
                try:
                    room = Room.objects.get(room_num=info['room_num'])
                    print(room)
                except Room.DoesNotExist:
                    return HttpResponse('没有这个房间')
                else:
                    try:
                        asset = Asset.objects.get(asset_name=info['asset_name'])
                    except Asset.DoesNotExist:
                        return HttpResponse('没有这个物品')
                    else:
                       
                        rom = Interchange.objects.filter(room=room).filter(asset=asset)
                        
                        print(rom[0])
                        
                        context = {'message':rom}
                        return render(request,'asset/api_asset_find.html',context)
                                                
    elif request.method == 'GET':

        return HttpResponse('获取方式有误')
         


#资产修改
def asset_alter(request):
    context = {}
    return render(request,'asset/asset_alter.html',context)

#资产修改运算

def asset_alter_db(request):
    info = dict(request.POST)
    print(info)
    return HttpResponse('ok')

#资产修改接口
@verify
def api_asset_change(request):
    """
        修改:{'楼号':'xx','楼层':'xx','房间号':'xx','名称':'xxx','数量':'xxx'}
    """
    if request.method == 'POST':
        info = request.POST
        print(info)
        try:
            tower = Tower.objects.get(tower_name=info['tower_num'])
        except Tower.DoesNotExist:
            return HttpResponse('没有这个楼')
        else:
            try:
                floor = Floor.objects.get(floor_num=info['floor_num'])
            except Floor.DoesNotExist:
                return HttpResponse('没有这个层')
            else:
                try:
                    room = Room.objects.get(room_num=info['room_num'])
                    print(room)
                except Room.DoesNotExist:
                    return HttpResponse('没有这个房间')
                else:
                    try:
                        asset = Asset.objects.get(asset_name=info['asset_name'])
                    except Asset.DoesNotExist:
                        return HttpResponse('没有这个物品')
                    else:
                       
                        rom = Interchange.objects.filter(room=room).filter(asset=asset)
                        
                        print(rom[0])
                        
                        
                            
                          
                        rom.update(asset_num=info['asset_num'])
                            
                      
                        return HttpResponse('成功修改')
                            
    elif request.method == 'GET':
        return HttpResponse('获取方式有误')
    

def query_site(request):
    """
        @author:吕琛琛
        @date:2018/10/19

        提交方式：POST
        提交格式：{'asset_name':'xxx'}
    """
    if request.method == 'GET':
        return HttpResponse(json.dumps({'message': '访问模式应该为POST'}))
    elif request.method == 'POST':
        info = dict(request.POST)
        try:
            asset_name = info['asset_name'][0]
        except KeyError:
            return HttpResponse(json.dumps({'message': "提交信息格式不对，或者键不是'asset_name'"}))
        else:
            try:
                an = Asset.objects.get(asset_name=asset_name)
            except Asset.DoesNotExist:
                return HttpResponse(json.dumps({'message': '所搜资产({})不存在'.format(asset_name)}))
            else:
                asset_obj = an.interchange_set.all()
                asset_list = []
                asset_dict = {asset_name: asset_list}
                b = {}
                for i in asset_obj:
                    b['房间号'] = i.room.room_num
                    b['数量'] = i.asset_num
                    asset_list.append(b)
                if not asset_list:
                    return HttpResponse(json.dumps({'message': '资产未分配或者未购买'}))
                return HttpResponse(json.dumps({'message': asset_dict}))


def asser_buyer(request):
    '''
    资产购买
    @account:薛威宁
    @time:2018/10/18
    方式:post
    提交数据库格式:{"asset_name"："xxx","pur_name"："x",user"："xx","save_room"："仓库"}
    仓库格式:{'asset_name':'xxx','room':'xxx','asset_num':'数字'}
    '''
    if request.method == 'POST':
        info = dict(request.POST)
        try:
            #获取楼
            to = Tower.objects.get(tower_name = info['save_tower'][0])
        except Tower.DoesNotExist:
            return HttpResponse('此楼不存在')
        else:
            try:
                fo = to.floor_set.get(floor_num = info['save_floor'][0])
            except Floor.DoesNotExist:
                return HttpResponse('楼层不存在')
            else:
                try:
                    ro = fo.room_set.get(room_num = info['save_room'][0])
                except Room.DoesNotExist:
                    return HttpResponse('房间不存在')
                else:
                    try:
                        us = User.objects.get(user_name = info['save_name'][0])
                    except User.DoesNotExist:
                        return HttpResponse('查无此人')
                    else:
                        try:
                            asset_name = Asset.objects.get(asset_name=info['asset_name'][0])

                        except Asset.DoesNotExist:
                            return HttpResponse('资产不再预购范围')

                        else:
                            try:
                                Interchange.objects.get(asset=asset_name)
                            except Interchange.DoesNotExist:
                                Interchange.objects.create(room=ro,
                                                           asset=asset_name,
                                                           asset_num=info['asset_num'][0])
                                return HttpResponse('资产已入库')
                            else:
                                Purchase.objects.create(save_room=ro,
                                                        user=us,
                                                        asset_name=asset_name,
                                                        pur_num=info['asset_num'][0])
                                io = Interchange.objects.get(asset=asset_name)
                                print(io)
                                io.asset_num = io.asset_num + int(info['asset_num'][0])
                                io.save()
                                print(io.asset_num)
                                return HttpResponse(json.dumps({'message': '资产购买成功'}))
    if request.method == 'GET':
        return render(request,'asset/asset_by.html')



#添加的要损坏的资产
def qq(request):
    return render(request,'asset/qq.html')


def damage_asset_add(request):
    """
        @author:刘宇
        @date:2018/10/19

        提交方式：POST
        提交格式：{'room_num':'xx','floor_num':'xx',
                    'tower_num':'xx','asset_name':'xxx','asset_num':'xx'}

    """
    if request.method == 'POST':
        info = request.POST
        print(info)
        try:
            tower = Tower.objects.get(tower_name=info['tower_num'])
        except Tower.DoesNotExist:
            return HttpResponse(json.dumps({'message':'没有这个楼'}))
        else:
            try:
                floor = tower.floor_set.get(floor_num=info['floor_num'])
            except Floor.DoesNotExist:
                return HttpResponse(json.dumps({'message':'没有这个层'}))
            else:
                try:
                    room = floor.room_set.get(room_num=info['room_num'])
                    print(room)
                except Room.DoesNotExist:
                    return HttpResponse(json.dumps({'message':'没有这个房间'}))
                else:
                    try:
                        asset = Asset.objects.get(asset_name=info['asset_name'])
                    except Asset.DoesNotExist:
                        return HttpResponse(json.dumps({'message':'没有这个物品'}))
                    else:
                        rom = Interchange.objects.filter(asset=asset).filter(room=room)
                        rom = rom[0]
                        rom.asset_num -= int(info['asset_num'])
                        
                        rom.damage_set.create(damage_num=info['asset_num'])
                        info_dict = {info['asset_name']:{'楼号':info['tower_num'],'层号':info['floor_num'],
                                     '房间号':info['room_num'],'损坏数量':info['asset_num']}}
                        DamageForm.objects.create(damageform=info_dict)
                        rom.save()
                        return HttpResponse(json.dumps({'message':'添加成功'}))
    if request.method == 'GET':
        return HttpResponse(json.dumps({'message':'获取方式为POST'}))
                         

#损坏的物品记录查找
def damage_find(request):
    context = {}
    return render(request,'asset/damage_find.html',context)

#@verify
def damage_asset_find(request):
    """
        @author:刘宇
        @date:2018/10/19

        提交方式：POST
        提交格式：{'room_num':'xx','asset_name':'xxx'}

    """
    if request.method == 'POST':
        
        info = request.POST
        print(info)
        find_name = info['asset_name']
        room = info['room_num']
        damage = DamageForm.objects.filter(bs_date__year=2018).filter(bs_date__month=10)
        info_dict = {}
        for i in damage:
            for key,value in eval(i.damageform).items():
                if key == find_name and value['房间号'] == room:
                    info_dict[key] = value
        
        context = {'aa':info_dict}
        return render(request,'asset/damage_find.html',context)

#损坏的资产记录删除
def damage_del(request):
    context = {}
    return render(request,'asset/damage_del.html',context) 


def damage_asset_del(request):
    """
        @author:刘宇
        @date:2018/10/19

        提交方式：POST
        提交格式：{'tower_num':'xx','room_num':'xx','asset_name':'xxx'}

    """
    if request.method == 'POST':
        info = request.POST
        find_name = info['asset_name']
        room = info['room_num']
        tower = info['tower_num']
        damage = DamageForm.objects.filter(bs_date__year=2018).filter(bs_date__month=10)
        info_dict = {}
        for i in damage:
            for key,value in eval(i.damageform).items():
                if key == find_name and value['房间号'] == room and value['楼号'] == tower:
                    info_dict[key] = value
        print(info_dict)
        if not info_dict:
            return HttpResponse(json.dumps({'message':'没有该记录'}))
        DamageForm.objects.get(damageform=info_dict).delete()
        return HttpResponse(json.dumps({'message':'删除成功'}))


@verify
def asset_inquire(request):

    """
        房间所有物资查询接口
        @auther: 辛光华
        @date: 2018/10/18
        本接口为资产详情查询接口,提交数据格式为{'tower_name': '教学楼',
                                            'floor_num': '3',
                                            'room_num': '311',
                                            'verify_pswd': '123'}

    """

    if request.method == "POST":

        info = dict(request.POST)

        try:

            tower = Tower.objects.get(tower_name=info['tower_name'][0])

        except Tower.DoesNotExist:

            return HttpResponse('没有这个楼')

        else:

            try:

                floor = tower.floor_set.get(floor_num=info['floor_num'][0])

            except Floor.DoesNotExist:

                return HttpResponse('这楼没这层')

            else:

                try:

                    room = floor.room_set.get(room_num=info['room_num'][0])

                except Room.DoesNotExist:

                    return HttpResponse('这层没这屋')

                else:

                    asset_obj = room.interchange_set.all()

                    asset_list = []

                    asset_dict = {room.room_num: asset_list}

                    x = {}

                    for i in asset_obj:

                        x[i.asset.asset_name] = i.asset_num

                    asset_list.append(x)

                    return HttpResponse(json.dumps(asset_dict))

    elif request.method == 'GET':

        return HttpResponse("不支持GET方式")
        
def receive_index(request):
    context = {'message': '欢迎来到本系统'}
    return render(request, 'asset/receive.html', context)

'''
        @author:王云峰,韩松
        @date:2018/10/25

        提交方式：POST
        提交格式：{<QueryDict: {'csrfmiddlewaretoken': ['yiuWU67Qja3AKAoiLZLG5tCUfxYGFGKW0vLo9r2j9AzbT6gkpQaRsQy9vf53iZsQ'],
        'tower_id': ['宿舍楼'], 'tier_id': ['3'], 'tier_id001': ['311'], 'tower_name': ['凳子'], 'tower_num': ['500'],
        'tower_id1': ['教学楼'], 'tier_id2': ['3'], 'tier_id3': ['311'], 'put_name': ['韩松']}>
'''

def receive_add(request):
    if request.method == 'GET':
        return HttpResponse("不支持GET方式")

    elif request.method == "POST":
        info = dict(request.POST)
        print(info)
        try:
            tower_name = Tower.objects.get(tower_name=info['tower_id'][0])
        except Tower.DoesNotExist:
            return HttpResponse('没有这栋楼')
        else:
            try:
                floor_num = Floor.objects.get(floor_num=info['tier_id'][0])
            except Floor.DoesNotExist:
                return HttpResponse('没有这层')
            else:
                try:
                    room_num = Room.objects.get(room_num=info['room'][0])
                except Room.DoesNotExist:
                    return HttpResponse('没有这房间')
                else:
                    try:
                        as_name = Asset.objects.get(asset_name=info['tower_name'][0])
                    except Asset.DoesNotExist:
                        return HttpResponse('没有这个物品')
                    else:
                        # as_num 数量
                        as_num = Interchange.objects.get(asset=as_name).asset_num

                        if as_num < int(info['tower_num'][0]):
                            return HttpResponse('数量不足')
                        elif as_num >= int(info['tower_num'][0]):
                                try:
                                    tower_name1 = Tower.objects.get(tower_name=info['tower_id1'][0])
                                except Tower.DoesNotExist:
                                    return HttpResponse('没有这栋楼')
                                else:
                                    try:
                                        floor_num1 = Floor.objects.get(floor_num=info['tier_id2'][0])
                                    except Floor.DoesNotExist:
                                        return HttpResponse('没有这层楼')
                                    else:
                                        try:
                                            room_num1 = Room.objects.get(room_num=info['room'][0])
                                        except Room.DoesNotExist:
                                            return HttpResponse('没有这房间')

                                        try:
                                            ly_user = Asset.objects.get(asset_name=info['tower_name'][0])
                                        except Asset.DoesNotExist:
                                            return HttpResponse('没有这个物品')
                                        try:
                                            user1 = InsideReceive.objects.get(ly_user=info['put_name'][0])
                                        except InsideReceive.DoesNotExist:
                                            return HttpResponse('没找到人1')
                                        else:

                                            try:
                                                user2 = InsideReceive.objects.get(jl_user=info['put_namee'][0])
                                            except InsideReceive.DoesNotExist:
                                                return HttpResponse('没找到人2')
                                            else:
                                                as_num_jian = as_num - int(info['tower_num'][0])


                                                as_num_jia = Receive.objects.create(receive=info['tower_name'][0])



                                                as_num_jia.save()
                                                InsideReceive.objects.create(as_name=info['tower_name'][0],as_num=info['tower_num'][0],
                                                                             ly_user=info['put_name'][0],jl_user=info['put_namee'][0],
                                                                             out_place=info['room'][0],in_place=info['room1'][0],
                                                                             jprice=info['tower_num2'][0],receive=as_num_jia
                                                                             )
                                                print(as_num_jia)
                                                print(as_num_jian)
                                                return HttpResponse('成功')















































